package util.remote;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import redis.clients.jedis.Jedis;
import util.AuthorConf;
import util.function.RemotoFunction;
import util.mysql.MysqlConnect;
import util.redis.RedisConnect;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 远程连接服务器
 * <p>
 * 远程连接 现网服务器 并连接数据库 将数据库端口转发到本地端口
 * <p>
 * <p>
 * Created by J.Chen on 2017/5/19.
 */
public class RemoteConnect {

    public static void connect(RemoteConf conf, RemotoFunction function) {
        JSch jsch = null;
        Session session = null;
        Connection connection = null;
        Jedis jedis = null;
        try {
            jsch = new JSch();
            jsch.addIdentity(AuthorConf.getAuth());
//            jsch.addIdentity("");
            session = jsch.getSession("kge", conf.getIp(), 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            System.out.println(session.getServerVersion());//这里打印SSH服务器版本信息

            //ssh -L 192.168.0.102:5555:192.168.0.101:3306 yunshouhu@192.168.0.102  正向代理
            int mysql_assinged_port = session.setPortForwardingL(conf.getMysqlConf().getLport(), conf.getMysqlConf().getRurl(), conf.getMysqlConf().getRport());//端口映射 转发
            System.out.println(conf.getRemoteType() + ":mysqlPort:" + mysql_assinged_port);
            int redis_assinged_port = session.setPortForwardingL(conf.getRedisConf().getLport(), conf.getRedisConf().getRurl(), conf.getRedisConf().getRport());//端口映射 转发
            System.out.println(conf.getRemoteType() + ":redisPort:" + redis_assinged_port);

            connection = MysqlConnect.connect(conf.getMysqlConf());
            jedis = RedisConnect.connect(conf.getRedisConf());
            function.execute(new RemoteConnectResult(jedis, connection, conf));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //在这里关闭连接 所以 单独的分析器中无需关闭 也不能关闭
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (jedis != null) {
                jedis.close();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }


}
